package com.nsgf.library.ui.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;

import com.kunminx.binding_recyclerview.adapter.BaseDataBindingAdapter;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.WaterInfoListBean;
import com.nsgf.library.databinding.ItemWaterFacilityBinding;
import com.nsgf.library.databinding.ItemWaterProjectHeaderBinding;

import java.util.ArrayList;
import java.util.List;

/**
 * 水情监测数据适配器（支持项目标题和设施项）
 */
public class WaterInfoAdapter extends ListAdapter<WaterInfoListBean, RecyclerView.ViewHolder> {

    private static final int TYPE_PROJECT_HEADER = 0;
    private static final int TYPE_FACILITY = 1;

    private Context mContext;
    private BaseDataBindingAdapter.OnItemClickListener<WaterInfoListBean> mOnItemClickListener;

    public WaterInfoAdapter(Context context) {
        super(new DiffUtil.ItemCallback<WaterInfoListBean>() {
            @Override
            public boolean areItemsTheSame(@NonNull WaterInfoListBean oldItem, @NonNull WaterInfoListBean newItem) {
                // 项目节点用projectCode，设施节点用facilityCode
                if (oldItem.isProjectNode() && newItem.isProjectNode()) {
                    return oldItem.getProjectCode() != null && 
                           oldItem.getProjectCode().equals(newItem.getProjectCode());
                } else if (oldItem.isFacilityNode() && newItem.isFacilityNode()) {
                    return oldItem.getFacilityCode() != null && 
                           oldItem.getFacilityCode().equals(newItem.getFacilityCode());
                }
                return false;
            }

            @Override
            public boolean areContentsTheSame(@NonNull WaterInfoListBean oldItem, @NonNull WaterInfoListBean newItem) {
                if (oldItem.isProjectNode() && newItem.isProjectNode()) {
                    return oldItem.getProjectCodeDesc() != null && 
                           oldItem.getProjectCodeDesc().equals(newItem.getProjectCodeDesc());
                } else if (oldItem.isFacilityNode() && newItem.isFacilityNode()) {
                    return oldItem.getFacilityCode() != null && 
                           oldItem.getFacilityCode().equals(newItem.getFacilityCode()) &&
                           (oldItem.getRz() != null ? oldItem.getRz().equals(newItem.getRz()) : newItem.getRz() == null) &&
                           (oldItem.getTm() != null ? oldItem.getTm().equals(newItem.getTm()) : newItem.getTm() == null);
                }
                return false;
            }
        });
        this.mContext = context;
    }

    public void setOnItemClickListener(BaseDataBindingAdapter.OnItemClickListener<WaterInfoListBean> onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }

    @Override
    public int getItemViewType(int position) {
        WaterInfoListBean item = getItem(position);
        if (item.isProjectNode()) {
            return TYPE_PROJECT_HEADER;
        } else {
            return TYPE_FACILITY;
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        if (viewType == TYPE_PROJECT_HEADER) {
            ItemWaterProjectHeaderBinding binding = DataBindingUtil.inflate(
                    inflater, R.layout.item_water_project_header, parent, false);
            return new ProjectHeaderViewHolder(binding);
        } else {
            ItemWaterFacilityBinding binding = DataBindingUtil.inflate(
                    inflater, R.layout.item_water_facility, parent, false);
            return new FacilityViewHolder(binding);
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        WaterInfoListBean item = getItem(position);
        if (holder instanceof ProjectHeaderViewHolder) {
            ((ProjectHeaderViewHolder) holder).bind(item);
        } else if (holder instanceof FacilityViewHolder) {
            ((FacilityViewHolder) holder).bind(item);
            if (mOnItemClickListener != null) {
                holder.itemView.setOnClickListener(v -> 
                    mOnItemClickListener.onItemClick(0, item, position));
            }
        }
    }

    /**
     * 将分层数据扁平化为列表
     */
    public void submitProjectList(List<WaterInfoListBean> projectList) {
        List<WaterInfoListBean> flatList = new ArrayList<>();
        if (projectList != null) {
            for (WaterInfoListBean project : projectList) {
                if (project.isProjectNode()) {
                    // 添加项目标题
                    flatList.add(project);
                    // 添加该项目的所有设施
                    if (project.getChildren() != null) {
                        // 将父项目的 projectCode 和 facilityType 传递给子设施
                        for (WaterInfoListBean facility : project.getChildren()) {
                            if (facility.getProjectCode() == null) {
                                facility.setProjectCode(project.getProjectCode());
                            }
                            // facilityType 可能需要从其他地方获取，暂时先不设置
                            flatList.add(facility);
                        }
                    }
                }
            }
        }
        submitList(flatList);
    }

    /**
     * 获取指定位置的项目（公共方法，用于外部访问）
     */
    public WaterInfoListBean getItemAt(int position) {
        if (position >= 0 && position < getItemCount()) {
            return getItem(position);
        }
        return null;
    }

    static class ProjectHeaderViewHolder extends RecyclerView.ViewHolder {
        private ItemWaterProjectHeaderBinding binding;

        ProjectHeaderViewHolder(ItemWaterProjectHeaderBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        void bind(WaterInfoListBean item) {
            binding.setVm(item);
            binding.executePendingBindings();
        }
    }

    static class FacilityViewHolder extends RecyclerView.ViewHolder {
        private ItemWaterFacilityBinding binding;

        FacilityViewHolder(ItemWaterFacilityBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        void bind(WaterInfoListBean item) {
            binding.setVm(item);
            binding.executePendingBindings();
        }
    }
}

